package com.leyou.search.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.naming.KeyNamingStrategy;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//@Component
public class JedisCache {
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private ObjectMapper mapper;

    //获取key的value值
    public String get(String key) throws IOException {
        Jedis jedis = jedisPool.getResource();
        String str = "";
        try {
            str = jedis.get(key);
            return str;
        } finally {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Map get(byte[] bytes) throws IOException {
        Jedis jedis = jedisPool.getResource();
        try {

            byte[] bytes1 = jedis.get(bytes);
            if(bytes1==null){
                return null;
            }
           Map map = mapper.readValue(bytes1, Map.class);
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String set(String key, Object value) throws JsonProcessingException {
        Jedis jedis = jedisPool.getResource();
        String str = "";
        try {
            if(value.getClass()==String.class){
                str = jedis.set(key, value+"");
            }else{
                byte[] k = mapper.writeValueAsBytes(key);
                byte[] v = mapper.writeValueAsBytes(value);
                str = jedis.set(k, v);
            }
        } finally {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    public String setex(String key, int seconds, String value) {
        Jedis jedis = jedisPool.getResource();
        String str = "";
        try {
            str = jedis.setex(key, seconds, value);
        } finally {
            try {
                jedis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return str;
    }





}
